import platform
import json
import os, sys
import random
import argparse

from PyQt5.QtWidgets import (
        QWidget, QApplication, QLabel, QPushButton
        )
from PyQt5.QtGui import (
        QPixmap, QPalette, QBrush
        )
from PyQt5.QtCore import (
        Qt, QTimer
        )

class Lottery(QWidget):
#class Lottery(QMainWindow):
    def __init__(self, tableRng, seatRng, bgImg):
        super(Lottery, self).__init__()
        self.tableRng = tableRng
        self.seatRng = seatRng
        desktop = QApplication.desktop()
        scr = desktop.screenGeometry()
        w, h = scr.width(), scr.height()
        self.bgImg = QPixmap(bgImg)
        self.bgImg = self.bgImg.scaled(w, h)
        self.isRun = False
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.operate)
        self.interval = 20

        self.setupUi()

        self.btnTrigger.clicked.connect(self.trigger)

    def setupUi(self):
        self.setWindowTitle("Lottery")
        self.setObjectName("Lottery")
        self.setAutoFillBackground(True)
        self.setWindowState(Qt.WindowFullScreen)
        #self.showFullScreen()
        self.resize(self.bgImg.width(), self.bgImg.height())
        palette = QPalette()
        palette.setBrush(QPalette.Background, QBrush(self.bgImg))
        self.setPalette(palette)

        self.btnTrigger = QPushButton(self)
        self.btnTrigger.setText('开始')
        self.btnTrigger.setFlat(True)
        self.btnTrigger.setVisible(False)

        self.lbTable = QLabel('00', self)

        self.lbSeat = QLabel('01', self)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            self.close()
        elif event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return:
            self.trigger()

    def setTableLE(self, x, y, size):
        self.tableX, self.tableY = x, y
        self.tableSize = size
        self.lbTable.move(self.tableX, self.tableY)
        self.lbTable.setStyleSheet('color:rgb(20, 20, 20);font-size:{}px;font-weight:bold'.format(self.tableSize))

    def setSeatLE(self, x, y, size):
        self.seatX, self.seatY = x, y
        self.seatSize = size
        self.lbSeat.move(self.seatX, self.seatY)
        self.lbSeat.setStyleSheet('color:rgb(20, 20, 20);font-size:{}px;font-weight:bold'.format(self.seatSize))

    def setIsShowBtn(self, isShow):
        self.btnTrigger.setVisible(False)

    def setInterval(self, interval):
        self.interval = interval

    def trigger(self):
        if self.isRun:
            self.timer.stop()
            self.btnTrigger.setText('停止')
        else:
            self.timer.start(self.interval)
            self.btnTrigger.setText('开始')
        self.isRun = not self.isRun

    def operate(self):
        self.lbTable.setText(random.choice(self.tableRng))
        self.lbSeat.setText(random.choice(self.seatRng))

def rng2list(strRng):
    try:
        bgn, end = strRng.split('-')
        return ['{:02d}'.format(i) for i in range(int(bgn), int(end) + 1)]
    except Exception as e:
        print(e)
    return []

if __name__ == '__main__':
    config = {
            'bgImg': 'bg.jpg',
            'tableRng': '1-35',
            'tableX': 880,
            'tableY': 600,
            'tableSize': 120,
            'seatRng': '1-10',
            'seatX': 880,
            'seatY': 850,
            'seatSize': 120,
            'isShowBtn': False,
            'interval': 60,
            }

    #parser = argparse.ArgumentParser()
    #parser.add_argument('--dumpCfg', action='store_true', help='dump config to cfg.json.')
    #args = parser.parse_args()

    if os.path.isfile('cfg.json'):
        with open('cfg.json', 'r') as fp:
            j = json.load(fp)
            for k, v in j.items():
                config[k] = v
    else:
        with open('cfg.json', 'w') as fp:
            json.dump(config, fp, indent=4)

    tableRng = rng2list(config['tableRng'])
    seatRng = rng2list(config['seatRng'])

    app = QApplication(sys.argv)
    lottery = Lottery(tableRng, seatRng, config['bgImg'])
    lottery.setTableLE(config['tableX'], config['tableY'], config['tableSize'])
    lottery.setSeatLE(config['seatX'], config['seatY'], config['seatSize'])
    lottery.setIsShowBtn(config['isShowBtn'])
    lottery.setInterval(config['interval'])
    lottery.show()
    sys.exit(app.exec_())
